﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Uber.Storage;
using System.Data;
using Uber.HabboHotel.GameClients;

namespace Uber.HabboHotel.Misc
{
    class RacingManager
    {
        int roomid;
        int mvalue;
        string[,] horses = null;

        int laststamp = 0;
        int currstamp = 0;

        public RacingManager()
        {
            roomid = 0;
            mvalue = 3;
            this.horses = makeHorses();

            laststamp = Convert.ToInt32(DateTime.Now.ToString("mmss"));
            currstamp = Convert.ToInt32(DateTime.Now.ToString("mmss"));
        }

        public void Update() {
            currstamp = Convert.ToInt32(DateTime.Now.ToString("mmss"));

            int offset = (laststamp > currstamp) ? 60 : 0;
            if (currstamp - laststamp + offset > 15) {
                laststamp = currstamp;
                using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
                {
                    int winner = this.getWinner();
                    this.giveMoney(winner);
                    this.AddRaceData(this.horses);
                    this.horses = makeHorses();
                }
            }
        }

        public int getWinner()
        {
            try
            {
                int val = 0;
                int winner = (new Random()).Next(0, 100);
                for (int i = 0; i < 5; i++)
                {
                    val += Convert.ToInt32(this.horses[i, 1]);
                    if (winner < val) return winner;
                }
                return 1;
            }
            catch (Exception e)
            {
                UberEnvironment.GetLogging().WriteLine("Winning Error: " + e.Message);
                return 1;
            }
        }

        public void giveMoney(int winning)
        {
            try
            {
                using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
                {
                    DataTable data = dbClient.ReadDataTable("SELECT * FROM horse_entries");
                    foreach (DataRow row in data.Rows)
                    {
                        GameClientManager gcm = UberEnvironment.GetGame().GetClientManager();
                        if (Convert.ToInt32(row["horseno"]) - 1 == winning)
                        {
                            string username = row["username"].ToString();
                            GameClient gc = gcm.GetClientByHabbo(gcm.GetIdByName(username));
                            bool online = Convert.ToBoolean(dbClient.ReadDataRow("SELECT * FROM users WHERE username='" + username + "'")["online"]);
                            if (online && gc.GetHabbo().CurrentRoomId == roomid)
                            {
                                int amount = Convert.ToInt32(row["amount"]);
                                int chance = Convert.ToInt32(this.horses[winning, 1]);
                                int pluscr = (amount) * (((100 - chance) / 10) / mvalue);
                                gc.GetHabbo().Credits += pluscr;
                                gc.GetHabbo().UpdateCreditsBalance(true);
                                gc.SendNotif("Your horse came first! you won " + pluscr + " credits with a modifier of " + (((100 - chance) / 10) / mvalue) + ".");
                            }
                        }
                        else
                        {
                            string username = row["username"].ToString();
                            GameClient gc = gcm.GetClientByHabbo(gcm.GetIdByName(username));
                            gc.SendNotif("Your horse came some other place then first, so you lost. Sorry!");
                        }
                    }
                }
            } catch(Exception e) {
                UberEnvironment.GetLogging().WriteLine("Racing Error: " + e.Message);
            }
        }

        public static void AddTicket(String username, int num, int amount)
        {
            using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
            {
                DataRow row = dbClient.ReadDataRow("SELECT * FROM horse_entries WHERE username='" + username + "'");
                if (row != null)
                {
                    dbClient.ExecuteQuery(String.Format("INSERT INTO horse_entries (horseno, amount, username) VALUES ('{0}', '{1}', '{2}')", num, amount, username));
                }
                else
                {
                    dbClient.ExecuteQuery(String.Format("UPDATE horse_entries SET horseno='{0}', amount='{1}' WHERE username='{2}'", num, amount, username));
                }
            }
        }

        public void AddRaceData(string[,] data)
        {
            using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
            {
                string query = "INSERT INTO horse_race VALUES (";
                for (int i = 0; i < 5; i++)
                {
                    string horse_data = data[i,0] + ":" + data[i,1];
                    query += "'" + horse_data + "', ";
                }
                query += "'" + DateTime.Now + "')";

                UberEnvironment.GetLogging().WriteLine(query);
                dbClient.ExecuteQuery(query);
            }
        }

        public string[,] makeHorses()
        {
            string[,] horses = new string[5,2];
            for (int i = 0; i < horses.Length; i++)
            {
                horses[i, 0] = "Horse no. " + i;
                horses[i, 1] = (35 - ((i+1) * 5)).ToString();
            }
            return horses;
        }
    }
}
